<template>
  <div class="divSize">
    <el-form
      ref="examRuleFormRef"
      :model="examInfo"
      status-icon
      :rules="examRules"
      label-width="80px"
      label-position="right"
      :inline="true"
    >
      <h1 style="font-size: 26px">
        预约考试<el-button style="margin-left: 10px" type="danger" size="small" @click="ResetExam"
          >重置</el-button
        >
      </h1>
      <br />
      <div style="margin-left: 5%">
        <h1>请选择你的考试时间:</h1>
        <br />
        <el-form-item prop="examDate">
          <el-date-picker
            :disabled="examDisabled"
            v-model="examInfo.examDate"
            placeholder="请选择"
            style="width: 350px"
            :disabled-date="examDisabledDateFun"
          /> </el-form-item
        ><br />
        <el-form-item prop="examTime">
          <el-time-select
            :disabled="examDisabled"
            style="width: 350px"
            v-model="examInfo.examTime"
            :start="examTime.examStartTime"
            step="00:10"
            :end="examTime.examEndTime"
            placeholder="选择时间"
            format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <span style="font-size: 16px; color: #545c64">考试状态: &nbsp;&nbsp;</span>
          <span v-if="examInfo.examState === '未考试'" style="color: #e6a23c">{{
            examInfo.examState
          }}</span>
          <span v-if="examInfo.examState === '已考试'" style="color: #409eff">{{
            examInfo.examState
          }}</span>
          <span v-else-if="examInfo.examState === '未通过'" style="color: #f56c6c">{{
            examInfo.examState
          }}</span>
          <span v-else-if="examInfo.examState === '已通过'" style="color: #67c23a">{{
            examInfo.examState
          }}</span>
          <span v-if="examInfo.examState === '未通过' || examInfo.examState === '已通过'">
            <span style="font-size: 16px; color: #545c64; margin-left: 40px"
              >考试分数: &nbsp;&nbsp;</span
            >
            {{ examInfo.examScore }}
          </span> </el-form-item
        ><br />

        <el-form-item>
          <el-button type="warning" @click="cancer">{{ cancerButton }}</el-button>
          <span style="margin-left: 175px"></span>
          <el-button
            :disabled="examDisabled"
            type="primary"
            @click="submitExamForm(examRuleFormRef)"
            >预约考试</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>

  <div class="divSize" style="margin-top: 3%">
    <el-form
      ref="exemptRuleFormRef"
      :model="exemptInfo"
      status-icon
      :rules="exemptRules"
      label-width="80px"
      label-position="right"
      :inline="true"
    >
      <h1 style="font-size: 26px">
        关于免试<el-button style="margin-left: 10px" type="danger" size="small" @click="ResetExem"
          >重置</el-button
        >
      </h1>
      <span style="font-size: 15px; color: #909399"
        >说明：前端技术栈或后端有项目可展示者可申请免试（面试时需要展示作品、项目），申请免试后无需预约考试</span
      ><br /><br />
      <div style="margin-left: 5%">
        <h1>申请免试理由</h1>
        <el-form-item prop="exemReason">
          <el-input
            v-model="exemptInfo.exemReason"
            maxlength="200"
            placeholder="请填写免试理由"
            show-word-limit
            type="textarea"
            resize="none"
            rows="5"
            style="width: 550px"
          />
        </el-form-item>
        <h1>若免试申请通过，选择你的面试时间:</h1>
        <el-form-item prop="exemDate">
          <el-date-picker
            v-model="exemptInfo.exemDate"
            placeholder="请选择"
            style="width: 230px"
            :disabled-date="exemDisabledDateFun"
          />
        </el-form-item>
        <el-form-item prop="exemTime">
          <el-select
            style="width: 230px"
            v-model="exemptInfo.exemTime"
            placeholder="选择时间"
            clearable
            @visible-change="visibleChange"
          >
            <el-option
              v-for="item in timeList"
              :key="item.value"
              :label="item.value"
              :value="item.value"
              :disabled="item.disable"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <span v-if="exemptInfo.exemState !== '合格' && exemptInfo.exemState !== '不合格'">
            <span style="font-size: 16px; color: #545c64">申请状态: &nbsp;&nbsp;</span>
            <span v-if="exemptInfo.exemState === '审核中'" style="color: #e6a23c">{{
              exemptInfo.exemState
            }}</span>
            <span v-if="exemptInfo.exemState === '已通过'" style="color: #67c23a">{{
              exemptInfo.exemState
            }}</span>
            <span v-else-if="exemptInfo.exemState === '未通过'" style="color: #f56c6c">{{
              exemptInfo.exemState
            }}</span>
          </span>
          <span v-if="exemptInfo.exemState === '合格' || exemptInfo.exemState === '不合格'">
            <span style="font-size: 16px; color: #545c64">免试中面试状态：&nbsp;&nbsp;</span>
            <span v-if="exemptInfo.exemState === '不合格'" style="color: #f56c6c">{{
              exemptInfo.exemState
            }}</span>
            <span v-if="exemptInfo.exemState === '合格'" style="color: #67c23a">{{
              exemptInfo.exemState
            }}</span>
            <span style="font-size: 16px; color: #545c64; margin-left: 40px"
              >面试分数: &nbsp;&nbsp;</span
            >
            {{ exemptInfo.exemScore }}
          </span> </el-form-item
        ><br />

        <el-form-item style="margin-left: 28%">
          <el-button type="primary" @click="submitExemForm(exemptRuleFormRef)">申请免试</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  clearByExamId,
  clearByExemId,
  getExamInfo,
  getExemInfoByDate,
  getExemptInfo,
  saveExamInfo,
  saveExemptInfo
} from '@/apis/bookExam'
import { userStore } from '@/stores/user'
import { getInfo } from '@/apis/signup'
import { getTimeInfo } from '@/apis/time'

const userstore = userStore()
const examRuleFormRef = ref<FormInstance>()
const exemptRuleFormRef = ref<FormInstance>()
const examDisabled = ref(true)
const cancerButton = ref('编辑预约')
const timeList = ref([{ value: '', disable: '' }])
const examTime = ref({
  examStartDate: '',
  examEndDate: '',
  examStartTime: '',
  examEndTime: ''
})
const examInfo = ref({
  examId: '',
  examDate: '',
  examTime: '',
  examState: '',
  examScore: ''
})
const exemTime = ref({
  exemStartDate: '',
  exemEndDate: '',
  exemStartTime: '',
  exemEndTime: ''
})
const exemptInfo = ref({
  exemId: '',
  exemReason: '',
  exemDate: '',
  exemTime: '',
  exemState: '',
  exemScore: ''
})
const getStudentInfo = () => {
  getInfo(userstore.userInfo.studentId).then((res) => {
    console.log('获取学生信息')
    if (res.data.code === 1) {
      console.log('获取成功')
      userstore.userInfo = res.data.data
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const getExam = () => {
  if (userstore.userInfo.examId != null && userstore.userInfo.examId != '') {
    getExamInfo(userstore.userInfo.examId).then((res) => {
      console.log('获取预约考试信息')
      if (res.data.code === 1) {
        console.log('获取成功')
        examInfo.value = res.data.data
        if (examInfo.value === null) {
          examInfo.value = {
            examId: '',
            examDate: '',
            examTime: '',
            examState: '',
            examScore: ''
          }
        }
        if (examInfo.value.examState != null && examInfo.value.examState != '') {
          if (examInfo.value.examState === '已通过') {
            ElMessageBox.alert('恭喜你通过考试，请尽快预约面试', '提示', {
              confirmButtonText: '确定',
              callback: () => {}
            })
          }
        }
      } else {
        console.log('获取失败')
        ElMessage({ type: 'error', message: res.data.msg })
      }
    })
  }
}

const getExempt = () => {
  if (userstore.userInfo.exemId != null && userstore.userInfo.exemId != '') {
    getExemptInfo(userstore.userInfo.exemId).then((res) => {
      console.log('获取申请免试信息')
      if (res.data.code === 1) {
        console.log('获取成功')
        exemptInfo.value = res.data.data
        if (exemptInfo.value === null) {
          exemptInfo.value = {
            exemId: '',
            exemReason: '',
            exemDate: '',
            exemTime: '',
            exemState: '',
            exemScore: ''
          }
        }
        if (exemptInfo.value.exemState != null && exemptInfo.value.exemState != '') {
          if (exemptInfo.value.exemState === '已通过') {
            ElMessageBox.alert('恭喜您通过免试审核，请在约定时间参加面试', '提示', {
              confirmButtonText: '确定',
              callback: () => {}
            })
          } else if (exemptInfo.value.exemState === '合格') {
            ElMessageBox.alert('恭喜您在免试中通过面试，欢迎加入软件卓越人才班', '提示', {
              confirmButtonText: '确定',
              callback: () => {}
            })
          } else if (exemptInfo.value.exemState === '不合格') {
            ElMessageBox.alert('很遗憾在免试中未通过面试，您还可以进行预约考试', '提示', {
              confirmButtonText: '确定',
              callback: () => {}
            })
          }
        }
      } else {
        console.log('获取失败')
        ElMessage({ type: 'error', message: res.data.msg })
      }
    })
  }
}

const getTime = () => {
  getTimeInfo().then((res) => {
    console.log('获取时间')
    if (res.data.code === 1) {
      console.log('成功')
      examTime.value = res.data.data
      exemTime.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}
onMounted(() => {
  examDisabled.value = true
  getExam()
  getExempt()
  getTime()
  userstore.defaultUrl = '/bookExam'
})
const ResetExam = () => {
  if (
    (Format(new Date()) > examTime.value.examStartDate &&
      Format(new Date()) < examTime.value.examEndDate) ||
    (Format(new Date()) > examTime.value.intvStartDate &&
      Format(new Date()) < examTime.value.intvEndDate)
  ) {
    ElMessage({ type: 'error', message: '本次卓越班报名还未结束，无法重置' })
  } else {
    ElMessageBox.alert('重置后将从后台清除该考试所有信息，包括分数与状态，请谨慎', '危险', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      showCancelButton: true,
      type: 'warning'
    })
      .then(() => {
        clearByExamId(examInfo.value.examId).then((res) => {
          if (res.data.code === 1) {
            ElMessage({ type: 'success', message: '操作成功' })
            getExam()
          } else {
            ElMessage({ type: 'error', message: res.data.msg })
          }
        })
      })
      .catch(() => {})
  }
}
const ResetExem = () => {
  if (
    (Format(new Date()) > exemTime.value.exemStartDate &&
      Format(new Date()) < exemTime.value.exemEndDate) ||
    (Format(new Date()) > exemTime.value.intvStartDate &&
      Format(new Date()) < exemTime.value.intvEndDate)
  ) {
    ElMessage({ type: 'error', message: '本次卓越班报名还未结束，无法重置' })
  } else {
    ElMessageBox.alert('重置后将从后台清除该免试所有信息，包括分数与状态，请谨慎', '危险', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      showCancelButton: true,
      type: 'warning'
    })
      .then(() => {
        clearByExemId(exemptInfo.value.exemId).then((res) => {
          if (res.data.code === 1) {
            ElMessage({ type: 'success', message: '操作成功' })
            getExempt()
          } else {
            ElMessage({ type: 'error', message: res.data.msg })
          }
        })
      })
      .catch(() => {})
  }
}
const examRules = reactive<FormRules<typeof examInfo>>({
  examDate: [{ required: true, message: '请选择预约考试时间', trigger: 'blur' }],
  examTime: [{ required: true, message: '请选择预约考试时间', trigger: 'blur' }]
})
const exemptRules = reactive<FormRules<typeof exemptInfo>>({
  exemReason: [{ required: true, message: '请填写免试理由', trigger: 'blur' }],
  exemDate: [{ required: true, message: '请选择面试时间', trigger: 'blur' }],
  exemTime: [{ required: true, message: '请选择面试时间', trigger: 'blur' }]
})
const visibleChange = (visible: boolean) => {
  if (visible) {
    if (exemptInfo.value.exemDate == '' || exemptInfo.value.exemDate == null) {
      timeList.value = []
      return
    }
    let time = exemTime.value.exemStartTime
    let i = 0
    while (parseInt(time.split(':')[0]) <= parseInt(exemTime.value.exemEndTime.split(':')[0])) {
      timeList.value[i] = { value: time, disable: false }
      let h = parseInt(time.split(':')[0])
      let m = parseInt(time.split(':')[1])
      if (parseInt(time.split(':')[0]) == parseInt(exemTime.value.exemEndTime.split(':')[0])) {
        while (parseInt(time.split(':')[1]) < parseInt(exemTime.value.exemEndTime.split(':')[1])) {
          i++
          m += 10
          time = [h, m, '00'].join(':')
          timeList.value[i] = { value: time, disable: false }
        }
        timeDisable()
        return
      }
      if (m < 60) {
        m += 10
      }
      if (m == 60) {
        h += 1
        m = 0
      }
      if (h < 10) h = '0' + h
      if (m < 10) m = '0' + m
      time = [h, m, '00'].join(':')
      i++
    }
  }
}
const timeDisable = () => {
  if (exemptInfo.value.exemDate != '' && exemptInfo.value.exemDate != null) {
    if (typeof exemptInfo.value.exemDate != 'string')
      exemptInfo.value.exemDate = Format(exemptInfo.value.exemDate)
    getExemInfoByDate(exemptInfo.value.exemDate).then((res) => {
      if (res.data.code === 1) {
        let exemList = res.data.data
        for (let i = 0; i < exemList.length; i++) {
          for (let j = 0; j < timeList.value.length; j++) {
            if (exemList[i].exemTime == timeList.value[j].value) {
              timeList.value[j].disable = true
            }
          }
        }
      } else {
        ElMessage({ type: 'error', message: res.data.msg })
      }
    })
  }
}
const cancer = () => {
  examDisabled.value = examDisabled.value === false
  if (cancerButton.value === '取消编辑') {
    if (examInfo.value.examId != null && examInfo.value.examId != '') {
      getExamInfo(examInfo.value.examId).then((res) => {
        examInfo.value = res.data.data
      })
    } else {
      examInfo.value = {}
    }
  }
  cancerButton.value = examDisabled.value === false ? '取消编辑' : '编辑预约'
}

const submitExamForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (examInfo.value.examState != '未考试' && examInfo.value.examState != '') {
        ElMessage({ type: 'error', message: '考试已完成，无法再次预约考试' })
        return false
      }
      if (Format(new Date()) >= examTime.value.examEndDate) {
        ElMessage({ type: 'error', message: '不在预约考试时间范围内' })
        return false
      }
      if (typeof examInfo.value.examDate != 'string')
        examInfo.value.examDate = Format(examInfo.value.examDate)
      examInfo.value.examState = '未考试'
      saveExamInfo(examInfo.value).then((res) => {
        if (res.data.code === 1) {
          examInfo.value = res.data.data
          examDisabled.value = true
          cancerButton.value = '编辑预约'
          ElMessage({ type: 'success', message: '预约成功' })
          getStudentInfo()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    } else {
      return false
    }
  })
}

const submitExemForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (typeof exemptInfo.value.exemDate != 'string')
        exemptInfo.value.exemDate = Format(exemptInfo.value.exemDate)
      if (exemptInfo.value.exemState != '审核中' && exemptInfo.value.exemState != '') {
        ElMessage({ type: 'error', message: '管理员已审核，无法再次申请' })
        getExempt()
        return false
      } else if (Format(new Date()) > exemTime.value.exemEndDate) {
        ElMessage({ type: 'error', message: '不在申请免试时间范围内' })
        return false
      } else {
        getExemInfoByDate(exemptInfo.value.exemDate).then((res) => {
          if (res.data.code === 1) {
            let exemList = res.data.data
            for (let i = 0; i < exemList.length; i++) {
              if (exemList[i].exemTime == exemptInfo.value.exemTime) {
                ElMessage({ type: 'error', message: '该时间已有人预约，请重试' })
                return false
              }
            }
          } else {
            ElMessage({ type: 'error', message: res.data.msg })
          }
        })
      }
      exemptInfo.value.exemState = '审核中'
      saveExemptInfo(exemptInfo.value).then((res) => {
        if (res.data.code === 1) {
          exemptInfo.value = res.data.data
          ElMessage({ type: 'success', message: '申请成功，已提交管理员审核' })
          getStudentInfo()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    } else {
      return false
    }
  })
}
function Format(date: Date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return year + '-' + month + '-' + day
}
const examDisabledDateFun = (date: Date) => {
  if (Format(date) >= examTime.value.examStartDate && Format(date) <= examTime.value.examEndDate)
    return false
  return true
}

const exemDisabledDateFun = (date: Date) => {
  if (Format(date) >= exemTime.value.exemStartDate && Format(date) <= exemTime.value.exemEndDate)
    return false
  return true
}
</script>

<style>
.inputSize {
  width: 220px;
  height: 30px;
}
.divSize {
  margin: 15px;
}

.el-icon {
  margin-left: 8px;
  margin-right: 8px;
}
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-left: 8px;
  margin-right: 6px;
}
</style>
